import { BigNumber } from 'bignumber.js';

// BigNumber.config({ DECIMAL_PLACES: 50 });

function throttle(fn, threshhold = 1000) {
    let last;
    let timer;

    return function (...args) {
        const context = this;
        const now = +new Date();

        if (last && now < last + threshhold) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(context, args);
            }, threshhold);
        } else {
            last = now;
            fn.apply(context, args);
        }
    };
}

function debounce(fn, delay = 1000) {
    let timer = null;

    return function (...args) {
        const context = this;
        clearTimeout(timer);

        timer = setTimeout(() => {
            fn.apply(context, args);
        }, delay);
    };
}

function transformLang(lang) {
    const arr = lang.split('-');

    // 如果没有 - 则认为没有地区
    if (arr.length === 1) {
        return lang;
    }

    // 把最后一个 - 分隔的字母转大写
    arr.splice(arr.length - 1, 1, arr.slice(-1)[0].toUpperCase());

    return arr.join('-');
}

function toNumberString(param) {
    // 过滤千分位
    param = String(param).replace(/,/g, '');

    // eslint-disable-next-line no-restricted-globals
    if (param === '' || isNaN(param)) {
        return '';
    }

    // 如果不是科学计数法
    if (String(param).toLowerCase().indexOf('e') === -1) {
        return param.toString();
    }

    return new BigNumber(param).toString(10);
}

function thousandSeparate(number) {
    if (typeof number === 'undefined' || number === '') {
        return '';
    }

    // 支持科学计数法
    // 如果非法，则返回空字符
    number = toNumberString(number);

    if (number === '') {
        return '';
    }

    const result = number.split('.');
    let leftNum = result[0].replace(/\D+/g, '').replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');

    // 如果是小数，且不是 -0  -0.0000
    if (number.substr(0, 1) === '-' && Number(number) !== 0) {
        leftNum = `-${leftNum}`;
    }

    if (result[1]) {
        // 如果是 -0.x 这样的小数
        return `${leftNum}.${result[1]}`;
    }

    return leftNum;
}

function precision(number, fixed = 2) {
    if (typeof number === 'undefined' || number === '') {
        return '';
    }

    // 支持科学计数法
    number = toNumberString(number);

    // 格式化精度
    fixed = parseInt(fixed, 10);

    // eslint-disable-next-line no-restricted-globals
    if (isNaN(number) || !number) {
        return fixed === 0 ? '0' : '0.'.padEnd(fixed + 2, '0');
    }

    const result = number.toString().split('.');
    const rightNum = `.${result[1] || ''}`;

    if (fixed === 0) { // 不要精度
        return result[0] === '-0' ? '0' : result[0];
    } else if (rightNum.length > fixed) { // 如果位数过长
        return result[0] + rightNum.substr(0, fixed + 1);
    }

    return result[0] + rightNum.padEnd(fixed + 1, '0');
}

export {
    throttle,
    debounce,
    transformLang,
    thousandSeparate,
    precision,
};
